﻿using System;
using System.Data;
using DbUp.Builder;
using DbUp.PgSql;
using Npgsql;

// NOTE: DO NOT MOVE THIS TO A NAMESPACE
// Since the class just contains extension methods, we leave it in the root so that it is always discovered
// and people don't have to manually add using statements.

/// <summary>
/// Configuration extension methods for PostgreSQL.
/// </summary>
// ReSharper disable CheckNamespace
public static class PgSqlExtensions
// ReSharper restore CheckNamespace
{
   /// <summary>
   /// Creates an upgrader for PostgreSQL databases.
   /// </summary>
   /// <param name="supported">Fluent helper type.</param>
   /// <param name="connectionFactory">The connection factory.</param>
   /// <returns>
   /// A builder for a database upgrader designed for PostgreSQL databases.
   /// </returns>
   public static UpgradeEngineBuilder PgSqlDatabase(this SupportedDatabases supported, Func<IDbConnection> connectionFactory)
   {
      var builder = new UpgradeEngineBuilder();
      builder.Configure(c => c.ConnectionFactory = connectionFactory);
      builder.Configure(c => c.ScriptExecutor = new PgSqlScriptExecutor(c.ConnectionFactory, () => c.Log, null, c.ScriptPreprocessors));
      builder.Configure(c => c.Journal = new PgSqlTableJournal(c.ConnectionFactory, null, "schemaversions", c.Log));
      return builder;
   }

   /// <summary>
   /// Creates an upgrader for PostgreSQL databases.
   /// </summary>
   /// <param name="supported">Fluent helper type.</param>
   /// <param name="connectionString">The connection string.</param>
   /// <returns>
   /// A builder for a database upgrader designed for PostgreSQL databases.
   /// </returns>
   public static UpgradeEngineBuilder PgSqlDatabase(this SupportedDatabases supported, string connectionString)
   {
      return supported.PgSqlDatabase(() => new NpgsqlConnection(connectionString));
   }
}
